package com.baoer.service.impl;

import cn.hutool.core.lang.UUID;
import com.baoer.R;
import com.baoer.dto.req.*;
import com.baoer.dto.resp.OperatorRespDTO;
import com.baoer.dto.resp.SaleRespDTO;
import com.baoer.dto.resp.UserRespDTO;
import com.baoer.mapper.UserMapper;
import com.baoer.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;

import static com.baoer.EmployeeIdGenerator.generateFiveDigitId;


/**
 * @Author: YING
 * @CreateTime: 2025-06-25
 * @Description:
 * @Version: 1.0
 */

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;

    @Value("${avatar.upload-dir}")
    private String uploadPath;
    @Override
    public R getUserInfo(UserInfoReqDTO userInfoReqDTO) {
        System.out.println("-----------------------" + userInfoReqDTO.toString());
        Integer pageIndex = userInfoReqDTO.getPageIndex();
        Integer pageSize = userInfoReqDTO.getPageSize();
        String phone = userInfoReqDTO.getPhone();
        String username = userInfoReqDTO.getUsername();
        String shopname = userInfoReqDTO.getShopname();
        pageIndex = (pageIndex - 1) * pageSize;
        double pageCount = userMapper.UserPageCount();
        pageCount = Math.ceil(pageCount / pageSize);
        List<UserRespDTO> list = userMapper.getUserInfoPage(phone, pageIndex,pageSize,username,shopname);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("pageCount", pageCount);
        map.put("UserRespDTO", list);
        return R.ok(map);
    }

    @Override
    public R updateUserInfo(UpdateuUserInfoReqDTO userInfoReqDTO) {
        Integer id = userInfoReqDTO.getId();
        String shopname = userInfoReqDTO.getShopname();
        Integer userid = userInfoReqDTO.getUserid();
        String phone = userInfoReqDTO.getPhone();
        String username = userInfoReqDTO.getUsername();
        userMapper.updateUserInfo(id,shopname,userid,phone,username);
        return R.ok();
    }

    @Override
    public R delUserInfo(Integer id) {
        userMapper.delUserInfo(id);
        return R.ok();
    }

    @Override
    public R addUserInfo(AddUserInfoReqDTO addUserInfoReqDTO) {
        Integer storeid = addUserInfoReqDTO.getStoreid();
        String phone = addUserInfoReqDTO.getPhone();
        Integer userid = addUserInfoReqDTO.getUserid();
        String username = addUserInfoReqDTO.getUsername();
        Integer id =generateFiveDigitId();
        userMapper.addUserInfo(storeid,phone,userid,username,id);
        return R.ok();
    }

    @Override
    public R getSaleInfo(GetSaleInfoReqDTO getSaleInfoReqDTO) {
        Integer pageIndex = getSaleInfoReqDTO.getPageIndex();
        Integer pageSize = getSaleInfoReqDTO.getPageSize();
        String username = getSaleInfoReqDTO.getUsername();
        String shopname = getSaleInfoReqDTO.getShopname();
        pageIndex = (pageIndex - 1) * pageSize;
        double pageCount = userMapper.SalePageCount();
        pageCount = Math.ceil(pageCount / pageSize);
        List<SaleRespDTO> list = userMapper.getSaleInfoPage( pageIndex,pageSize,username,shopname);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("pageCount", pageCount);
        map.put("UserRespDTO", list);
        return R.ok(map);
    }

    @Override
    public R getOperatorInfo(GetOperatorInfoReqDTO getOperatorInfoReqDTO) {
        Integer pageIndex = getOperatorInfoReqDTO.getPageIndex();
        Integer pageSize = getOperatorInfoReqDTO.getPageSize();
        String username = getOperatorInfoReqDTO.getUsername();
        String shopname = getOperatorInfoReqDTO.getShopname();
        String phone = getOperatorInfoReqDTO.getPhone();
        pageIndex = (pageIndex - 1) * pageSize;
        double pageCount = userMapper.OperatorPageCount();
        pageCount =(int) Math.ceil(pageCount / pageSize);
        List<OperatorRespDTO> list = userMapper.getOperatorInfoPage(phone, pageIndex,pageSize,username,shopname);
        System.out.println(list.size());
        HashMap<Object, Object> map = new HashMap<>();
        map.put("pageCount", pageCount);
        map.put("UserRespDTO", list);
        return R.ok(map);
    }

    @Override
    public R addOperatorInfo(AddOperatorInfoReqDTO addOperatorInfoReqDTO) {
//        Integer storeid = addOperatorInfoReqDTO.getStoreid();
//        MultipartFile avatar = addOperatorInfoReqDTO.getAvatar();
//        String phone = addOperatorInfoReqDTO.getPhone();
//        Integer userid = addOperatorInfoReqDTO.getUserid();
//        String username = addOperatorInfoReqDTO.getUsername();
//        uploadAvatar(userid,avatar);
//        userMapper.addOperatorInfo(storeid,avatar,phone,userid,username);
        String avatarUrl = "";
        if (addOperatorInfoReqDTO.getAvatar() != null
                && !addOperatorInfoReqDTO.getAvatar().isEmpty()) {
            try {
                avatarUrl = uploadAvatarFile(addOperatorInfoReqDTO.getAvatar());
            } catch (IOException e) {
                return R.ok("头像上传失败");
            }
        }
        // 2. 提取用户信息
        Integer storeid = addOperatorInfoReqDTO.getStoreid();
        String phone = addOperatorInfoReqDTO.getPhone();
        Integer userid = addOperatorInfoReqDTO.getUserid();
        String username = addOperatorInfoReqDTO.getUsername();

        // 3. 调用Mapper
        userMapper.addOperatorInfo(storeid, avatarUrl, phone, userid, username);
        return R.ok();
    }
    private String uploadAvatarFile(MultipartFile file) throws IOException {
        // 1. 创建存储目录
        Path uploadDir = Paths.get(uploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        // 2. 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + fileExtension;

        // 3. 保存文件
        Path filePath = uploadDir.resolve(newFileName);
        Files.copy(file.getInputStream(), filePath);
        // 4. 返回访问URL
        return "/avatars/" + newFileName;
    }
    @Override
    public R getstoreInfo() {
        return R.ok(userMapper.getstoreInfo());
    }

    @Override
    public R getheadstoreInfo() {
        return R.ok(userMapper.getheadstoreInfo());
    }
}

